package javango.contrib.galoot;

import galoot.ContextStack;
import galoot.Template;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javango.http.HttpException;
import javango.http.HttpResponse;

public class GalootResponse extends HttpResponse {

	private final static Log log = LogFactory.getLog(GalootResponse.class);
	
	protected String template;
	protected Map<String, Object> context;
	
	static {
	}
	
	public void renderToWriter(Writer writer) throws HttpException {
		try {
			Template t = new Template(new File(template));
			t.render(new ContextStack(context), writer);
			writer.flush();
		} catch (IOException e) {
			log.error(e,e);
			throw new HttpException(e);
		}
	}
	public void render(HttpServletRequest req, HttpServletResponse resp) throws HttpException {
		try {
			renderToWriter(new OutputStreamWriter(resp.getOutputStream()));
		} catch (IOException e) {
			log.error(e,e);
			throw new HttpException(e);
		}
	}

	public GalootResponse(String template, Map<String, Object> context) {
		this.template = template;
		this.context = context;
	}

	public String getTemplate() {
		return template;
	}
	
	@Override
	public Map<String, Object> getContext() {
		return context;
	}

}
